What is the purpose of the UNION operator in SQL and how does it work?
What is the purpose of the UNION operator in SQL and how does it work?
397
30-Jun-2023
Updated on 18-Nov-2023
Aryan Kumar
18-Nov-2023The UNION operator in SQL is used to combine the result sets of two or more SELECT statements into a single result set. The purpose of the UNION operator is to merge rows from different tables or queries while removing duplicate rows from the final result set. Each SELECT statement within the UNION must have the same number of columns in the result sets, and the corresponding columns must have compatible data types.
Here's a basic syntax of the UNION operator:
Key points about the UNION operator:
Columns and Data Types:
Duplicates Removal:
Ordering:
NULL Handling:
Here's a simple example to illustrate the use of the UNION operator:
In this example, the UNION operator is used to combine the results of two SELECT statements. The result will include distinct employee records from both the HR and IT departments.
It's worth noting that the UNION operator is different from the JOIN operation, which is used to combine rows from two or more tables based on a related column between them. UNION, on the other hand, is used to combine rows from the result sets of two or more SELECT statements.